import { Ref } from "vue";
import { getFromOneByAsync, saveOneByAsync } from "@/utils/utools/DbStorageUtil";
import { SeniorFileContent } from "@/entity/SeniorFileItem";
import LocalNameEnum from "@/enumeration/LocalNameEnum";
import { parseRestRequests } from "$/util";
import { useUrlStore } from "@/store";
import MessageUtil from "@/utils/model/MessageUtil";
import { clientSearchSeniorApi } from "@/api";

export type { Ref };

export interface UseSeniorFileItemContent {
  id: string;
  /**
   * 编辑器宽度
   */
  size: Ref<number>;
  /**
   * 脚本内容
   */
  content: Ref<string>;
  /**
   * 是否已经完成初始化
   */
  init: Ref<boolean>;
  /**
   * 加载中
   */
  loading: Ref<boolean>;
  /**
   * 查询结果
   */
  data: Ref<string | undefined>;
  /**
   * 保存操作
   */
  save: () => Promise<void>;

  /**
   * 执行查询
   */
  run: (index: number) => void;
}

export const useSeniorFileItemContent = (id: string): UseSeniorFileItemContent => {
  const content = ref("");
  const size = ref(50);
  let rev: string | undefined = undefined;
  const init = ref(false);

  const { run, data, loading } = useRequest(
    (index: number) => {
      const requests = parseRestRequests(content.value);
      const request = requests[index];
      if (!request) {
        return Promise.reject(new Error("请求块无法识别"));
      }
      const { id } = useUrlStore();
      if (!id) return Promise.reject(new Error("请选择链接"));
      return clientSearchSeniorApi(id, request);
    },
    {
      manual: true,
      onError: (error) => {
        MessageUtil.error("请求错误", error);
      }
    }
  );

  (async () => {
    const res = await getFromOneByAsync<SeniorFileContent>(
      LocalNameEnum.ITEM_SENIOR_FILE_ITEM_ + id
    );
    content.value = res.record?.content || "";
    size.value = res.record?.size || 50;
    rev = res.rev;
  })().finally(() => (init.value = true));

  const save = async () => {
    rev = await saveOneByAsync<SeniorFileContent>(
      LocalNameEnum.ITEM_SENIOR_FILE_ITEM_ + id,
      {
        content: content.value,
        size: size.value
      },
      rev
    );
  };

  return {
    id,
    content,
    init,
    loading,
    size,
    data,
    save,
    run
  };
};
